import ala from 'ala'
import api from 'api'
import Vue from 'vue'
// 根据Url中的参数Id，获取视图
// 使用动态 动态网址 Api/{{表名}}/ViewById

export async function getView (apiUrl, append) {
  var para = {
    id: this.getId()
  }
  if (append) {
    para = {
      ...para,
      ...append
    }
  }
  var response = await ala.httpGet(apiUrl, para, append)
  if (response) {
    return response
  }
}

// 保存
// 动态保存接口： Api/{{表名}}/QuerySave
export async function save (apiUrl, viewModel) {
  var para = {
    ...viewModel
  }
  var response = await Vue.prototype.$ala.httpPost(apiUrl, para)
  // 继续或返回上一页
  if (response) {
    ala.toMessage('操作成功')
  }
}


// 获取边框
export function getBorder (typeBorder, widgetValue) {
  var borderModel = {
    title: '',
    icon: '',
    description: '',
    type: ''
  }
  if (typeBorder) {
    borderModel = typeBorder // 使用服务返回的数据
  }
  if (widgetValue) {
    borderModel = widgetValue
  }
  if (!borderModel.title) {
    var currentMenu = ala.vuexLocalGet(ala.themeCurrentMenuCacheKey())
    if (currentMenu) {
      borderModel.title = currentMenu.name
    }
  }
  return borderModel
}



// 根据路由获取类型
export function getType (route, widgetType) {
  if (route.query !== undefined && route.query.Type !== undefined) {
    return route.query.Type
  }
  if (widgetType !== undefined && widgetType.type !== undefined) {
    return widgetType.type
  }
  if (route.meta !== undefined && route.meta.type !== undefined) {
    return route.meta.type
  }
}



// 获取URL中的ID
export function getId () {
  var route = ala.router()
  if (route.query !== undefined && route.query.id !== undefined) {
    return route.query.id
  }
  if (route.query !== undefined && route.query.Id !== undefined) {
    return route.query.Id
  }
  if (route.query !== undefined && route.query.ID !== undefined) {
    return route.query.ID
  }
  return 0
}


// 将url参数解析为一个对象
export function routeToObject (route) {
  var str = route.fullPath
  var index = str.indexOf('?', 0)
  str = str.substring(index + 1, str.length)
  var result = {}
  var temp = str.split('&')
  for (var i = 0; i < temp.length; i++) {
    var temp2 = temp[i].split('=')
    result[temp2[0]] = temp2[1]
  }
  return result
}